package web;

import com.fasterxml.jackson.databind.ObjectMapper;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> msg = new HashMap<>(8);
        String avatar = request.getParameter("avatar");
        String name = request.getParameter("name");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        UserService us = new UserServiceImpl();
        try{
            us.register("/avatar.jpg",name,username,password,email);
            msg.put("msg","注册成功");
            request.getRequestDispatcher("my.html").forward(request,response);
        }catch (Exception e) {
            e.printStackTrace();
            msg.put("msg", "注册失败，请稍后再试");
        }finally {
            new ObjectMapper().writeValue(response.getOutputStream(),msg);
        }
    }
}
